#include "uidhelper.h"
#include "ui_uidhelper.h"

UIDHelper::UIDHelper(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::UIDHelper)
{
    ui->setupUi(this);
    uiInit();
}

// 将数字转换为35进制字符
QString UIDHelper::toBase35(int number) {
    if (number < 0 || number >= 35) {
        return QString();  // 超出范围返回空字符串
    }
    return QString(base35Chars[number]);
}

// 将日期转换为自定义的35进制表示法
QString UIDHelper::dateToBase35(int year, int month, int day) {
    // 计算年份的后两位
    int yearLastTwoDigits = year % 100;
    int yearFirstDigit = yearLastTwoDigits / 10;
    int yearSecondDigit = yearLastTwoDigits % 10;

    // 将年份的后两位转换为35进制
    QString yearStrFirst = toBase35(yearFirstDigit - 1);
    QString yearStrSecond = toBase35(yearSecondDigit - 1);

    // 将月份和日期转换为35进制
    QString monthStr = toBase35(month - 1);  // 月份从1开始，需要减1
    QString dayStr = toBase35(day - 1);      // 日期从1开始，需要减1

    base35Date = yearStrFirst + yearStrSecond + monthStr + dayStr;

    // 拼接结果
    return base35Date;
}

void UIDHelper::getDateNow()
{
    // 获取当前日期
    QDate currentDate = QDate::currentDate();

    // 获取年、月、日
    year = currentDate.year();
    month = currentDate.month();
    day = currentDate.day();

    dateToBase35(year, month, day);
    ui->le_3->setText(base35Date);
}

void UIDHelper::focusNextLineEdit() {
    QLineEdit* currentLineEdit = qobject_cast<QLineEdit*>(sender());
    if (currentLineEdit->text().length() == 1) {
        if (currentLineEdit && currentLineEdit == ui->lineEdit) {
            ui->lineEdit_2->setFocus();
            ui->lineEdit_2->selectAll();
        } else if (currentLineEdit == ui->lineEdit_2) {
            ui->lineEdit_3->setFocus();
            ui->lineEdit_3->selectAll();
        } else if (currentLineEdit == ui->lineEdit_3) {
            ui->lineEdit_4->setFocus();
            ui->lineEdit_4->selectAll();
        }
    }
}

void UIDHelper::uiInit()
{
    // QIcon program_ico(":/ui/res/ProgramIcon.png");
    ui->le->clear();    // 清空提示信息
    // ui->le_2->clear();
    // 创建一个QFont对象，设置字体大小
    QFont font = ui->le_2->font();
    font.setPointSize(15);  // 设置字体大小为20

    // 将QFont应用到QLabel
    ui->le_2->setFont(font);
    ui->le_2->setText("FFFFFFFF");
    ui->le_3->setFont(font);
    getDateNow();
    ui->lineEdit->setFont(font);
    ui->lineEdit_2->setFont(font);
    ui->lineEdit_3->setFont(font);
    ui->lineEdit_4->setFont(font);
    ui->lineEdit->setText("0");
    ui->lineEdit_2->setText("0");
    ui->lineEdit_3->setText("0");
    ui->lineEdit_4->setText("0");
    ui->lineEdit->setValidator(new QRegExpValidator(QRegExp("[0-9]{1}")));
    ui->lineEdit_2->setValidator(new QRegExpValidator(QRegExp("[0-9]{1}")));
    ui->lineEdit_3->setValidator(new QRegExpValidator(QRegExp("[0-9]{1}")));
    ui->lineEdit_4->setValidator(new QRegExpValidator(QRegExp("[0-9]{1}")));
    connect(ui->lineEdit, &QLineEdit::textChanged, this, &UIDHelper::focusNextLineEdit);
    connect(ui->lineEdit_2, &QLineEdit::textChanged, this, &UIDHelper::focusNextLineEdit);
    connect(ui->lineEdit_3, &QLineEdit::textChanged, this, &UIDHelper::focusNextLineEdit);
    connect(ui->lineEdit_4, &QLineEdit::textChanged, this, &UIDHelper::focusNextLineEdit);

    on_btnrefresh_clicked();    // 刷新串口
    // ui->label->hide();
    // ui->cmbportname->hide();
    ui->widget_2->hide();
    ui->charReadRadioButton->setChecked(true);
    _scanPortTimer = new QTimer(this);
    connect(_scanPortTimer, SIGNAL(timeout()), this, SLOT(messlot()));
    _scanPortTimer->start(500);
    ui->btnopen->setEnabled(false);
    ui->cmbportname->setEnabled(true);
    // ui->cmbportname->setFixedSize(70, 20);
    ui->btnrefresh_3->setEnabled(false);
    ui->btnrefresh_6->setEnabled(false);
}

UIDHelper::~UIDHelper()
{
    delete ui;
}

void UIDHelper::on_btnopen_clicked()
{
    if (ui->btnopen->text() == "打开串口")
    {
        ui->cmbportname->setEnabled(true);
        ui->btnrefresh_3->setEnabled(true);
        ui->btnrefresh_4->setEnabled(true);
        ui->btnrefresh_6->setEnabled(true);
        if(!ui->cmbportname->currentText().isEmpty())
        {
            m_serial.setPortName(ui->cmbportname->currentText());
            m_serial.setBaudRate(ui->cmbportbaud->currentText().toInt());
        }
        switch (ui->bit->currentIndex())  //  设置数据位数
        {
        case 8:m_serial.setDataBits(QSerialPort::Data8); break;
        default: break;
        }
        switch (ui->check->currentIndex())  //  设置奇偶校验
        {
        case 0: m_serial.setParity(QSerialPort::NoParity); break;
        case 1: m_serial.setParity(QSerialPort::OddParity); break;
        case 2: m_serial.setParity(QSerialPort::EvenParity); break;
        default: break;
        }
        switch (ui->stopbit->currentIndex())  //  设置停止位
        {
        case 1: m_serial.setStopBits(QSerialPort::OneStop); break;
        case 2: m_serial.setStopBits(QSerialPort::TwoStop); break;
        default: break;
        }
        m_serial.open(QIODevice::ReadWrite);
        if(m_serial.isOpen())
        {
            canRead = 1;
            m_serial.write("AT+UID -?\r\n");

            ui->le->setText("串口打开成功");
            connect(&m_serial,SIGNAL(readyRead()),this,SLOT(messlot()));
            ui->btnopen->setText("关闭串口");
            // connect(&m_serial,&QSerialPort::readyRead,this,&Mserialport::messlot);
        }else{
            ui->le->setText("串口打开失败");
            // newportName.clear();
            // ui->cmbportname->clear();
            ui->btnopen->setEnabled(false);
            ui->btnrefresh_3->setEnabled(false);
            ui->btnrefresh_4->setEnabled(false);
            ui->btnrefresh_6->setEnabled(false);
            ui->cmbportname->setEnabled(true);
        }
    }else  // 关闭串口
    {
        ui->cmbportname->setEnabled(true);
        ui->btnrefresh_3->setEnabled(false);
        ui->btnrefresh_4->setEnabled(false);
        ui->btnrefresh_6->setEnabled(false);
        // ui->le_2->clear();
        m_serial.close();
        if(m_serial.isOpen())
        {
            ui->le->setText("串口关闭失败！！！");
        }else{
            m_serial.close();
            ui->le_2->setText("FFFFFFFF");
            canRead = 0;
            ui->btnopen->setText("打开串口");
            ui->le->setText("串口关闭成功");
        }
    }
}

// 串口接收信息的处理函数
void UIDHelper::messlot()
{
    QByteArray arrayrecv;
    arrayrecv= m_serial.readAll();
    lastLine = arrayrecv;
    if (!lastLine.isNull()) {
        if(lastLine.contains("AT+OK", Qt::CaseSensitive))  //判断是否带有AT+OK字符串
        {
            if(lastLine.contains("-d", Qt::CaseSensitive))  //判断是否带有 -d 字符串
            {
                if(canRead){
                    canRead = 0;
                    readUID();
                }
            }else
            {
                canRead = 1;
                m_serial.write("AT+UID -?\r\n");
            }
        }else if(lastLine.contains("AT+KEY", Qt::CaseSensitive))  //当发送AT+UID -dBDJ50001 进行写入的时候，会收到串口回复AT+KEY，此时，再次发送AT+UID -k123456，123456为写入UID的秘钥
        {
            m_serial.write("AT+UID -k123456\r\n");
        }else if(lastLine.contains("AT+ERR", Qt::CaseSensitive))  //当回复的是AT+ERR时，则判定为写入/读取UID失败
        {
            ui->le_2->setText("读取错误，请重新读取");
            try {
                QString frameStr = lastLine.mid(9, 3);  //从索引9开始截取3个字符
                frame = frameStr.toInt();  //将截取的字符串转换为整数
            } catch (...) {
                qDebug() << "截取数据包帧数目异常.";
                frame--; // 出错时将 frame 减1
            }
        }
    }
}

void UIDHelper::readUID()
{
    QString trimmedStr = lastLine.trimmed();
    QString readUID = trimmedStr.section('-', 1, 1);
    QString UID = readUID.trimmed().mid(1);
    ui->le_2->setText(UID);
}


void UIDHelper::on_charReadRadioButton_clicked()
{
    if(ui->charReadRadioButton->isChecked())
        at = 1;
    else
        at = 0;
}

void UIDHelper::on_btnrefresh_clicked()
{
    m_serial.close();
    ui->btnopen->setText("打开串口");
    ui->btnrefresh_3->setEnabled(false);
    ui->btnrefresh_4->setEnabled(false);
    ui->btnrefresh_6->setEnabled(false);
    ui->cmbportname->clear();
    // ui->le_2->clear();
    int nn = ui->cmbportname->count();
    for (int i =nn-1;i>-1; i--)
    {
        ui->cmbportname->removeItem(i);
    }
    // 清空串口名
    ui->btnopen->setEnabled(true);

    // 创建一个 QStringList 数组来接收所有存在的串口名称
    QStringList currentPortNames;

    // 遍历串口信息
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->cmbportname->addItem(info.portName());
        currentPortNames << info.portName();
        qDebug() << "All port :" << currentPortNames;
    }

    if (currentPortNames.size() == 1) {
        newportName = currentPortNames.at(0);
    }else
    {
        // 对比当前的串口名称列表和上一次的串口名称列表，找出新增的串口
        foreach (const QString &portName, currentPortNames)
        {
            if (!lastPortNames.contains(portName))
            {
                newportName = portName;
                qDebug() << "New port added:" << portName;
            }
        }
    }

    // 设置组合框的当前选中项为新增的串口
    if (!newportName.isEmpty()) {
        int index = ui->cmbportname->findText(newportName);
        if (index != -1) {
            ui->cmbportname->setCurrentIndex(index);
        }
    }

    // 更新上一次的串口名称列表
    lastPortNames = currentPortNames;

    ui->le->setText("已经刷新串口");
}

void UIDHelper::on_btnrefresh_3_clicked()
{
    QString inputText = ui->lineEdit->text();
    QString inputText_2 = ui->lineEdit_2->text();
    QString inputText_3 = ui->lineEdit_3->text();
    QString inputText_4 = ui->lineEdit_4->text();

    QString inputUID = base35Date + inputText + inputText_2 + inputText_3 + inputText_4;
    QString writeAT = "AT+UID -d" + inputUID + "\r\n";
    m_serial.write(writeAT.toUtf8());

}

void UIDHelper::MySleep(int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

void UIDHelper::on_btnrefresh_4_clicked()
{
    QString inputText_4 = ui->lineEdit_4->text();
    int inputNext_4 = inputText_4.toInt() + 1;
    if (inputNext_4 == 10)
    {
        inputNext_4 = 0;
    }
    ui->lineEdit_4->setText(QString::number(inputNext_4));
}

void UIDHelper::on_btnrefresh_6_clicked()
{
    // ui->le_2->clear();
    ui->btnrefresh_6->setEnabled(true);
    canRead = 1;
    m_serial.write("AT+UID -?\r\n");
}
